package com.daxia.bumall.service;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.daxia.bumall.common.AppPropertyKey;
import com.daxia.bumall.config.AppProperties;
import com.daxia.bumall.dao.CityDAO;
import com.daxia.bumall.dao.DistrictDAO;
import com.daxia.bumall.dto.DistrictDTO;
import com.daxia.bumall.dto.GPSAddressDTO;
import com.daxia.bumall.model.City;
import com.daxia.bumall.model.District;

/**
 * http://developer.baidu.com/map/index.php?title=webapi/guide/webservice-geocoding
 * 
 */
@Service
public class BaiduMapService {
    private static Logger logger = Logger.getLogger(BaiduMapService.class);
    
    @Autowired
    private DistrictDAO districtDAO;
    @Autowired
    private CityDAO cityDAO;
    
    public GPSAddressDTO getAddressByGPS(Double lat, Double lng) {
        try {
            return doGetAddress(lat, lng);
        } catch (IOException e) {
            logger.error(e, e);
        }
        return null;
    }

    private GPSAddressDTO doGetAddress(Double lat, Double lng) throws IOException {
        String url = "http://api.map.baidu.com/geocoder/v2/?ak={key}&location={lat},{lng}&output=json";
        url = url.replace("{key}", AppProperties.get(AppPropertyKey.BaiduKey));
        url = url.replace("{lat}", lat + "");
        url = url.replace("{lng}", lng + "");
        
        Document doc = Jsoup.connect(url).get();
        String jsonText = doc.text();
        
        JSONObject json = JSONObject.parseObject(jsonText);
        if (json.getInteger("status") != 0) {
            return null;
        }

        json = json.getJSONObject("result");
        json = json.getJSONObject("addressComponent");
        
        String districtName = json.getString("district");
        String cityName = json.getString("city");
        
        if (logger.isDebugEnabled()) {
            logger.debug("districtName: " + districtName + ", cityName: " + cityName);
        }
        
        DistrictDTO districtDTO = new DistrictDTO();
        districtDTO.setName(districtName);
        districtDTO.setCity(new City());
        districtDTO.getCity().setName(cityName);
        District district = districtDAO.findOne(districtDTO);
        if (district != null) {
            GPSAddressDTO address = new GPSAddressDTO();
            address.setDistrict(district);
            address.setCity(district.getCity());
            address.setProvince(district.getCity().getProvince());
            return address;
        }

        City city = cityDAO.findByName(cityName);
        if (city != null) {
            GPSAddressDTO address = new GPSAddressDTO();
            address.setCity(city);
            address.setProvince(city.getProvince());
            return address;
        }
        
        return null;
    }
    
    public static void main(String[] args) throws Exception {
        new BaiduMapService().getAddressByGPS(28.11664, 113.003286);
    }
    
}
